package com.sp.system.user.service.impl;

import com.ananjt.system.vo.SecurityUserDetails;
import com.ananjt.system.vo.UserRoleVo;
import com.sp.system.user.core.exception.TokenVerifyException;
import com.sp.system.user.core.utils.enums.PermissionEnum;
import com.sp.system.user.service.SpUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    private SpUserService userService;

    /**
     * @Description:加载用户信息&权限
     * @param: username 用户名
     * @Return: org.springframework.security.core.UserDetails
     * @Author: chenanhai
     * @Date: 2019年9月5日
     */

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        SecurityUserDetails userDetails = new SecurityUserDetails();
        UserRoleVo userRoleVo = userService.getSystemUserByLoginName(loginName);
        if (userDetails != null) {
            BeanUtils.copyProperties(userRoleVo, userDetails);
            return userDetails;
        } else {
//            return ContentResult.errorResult(null,"用户名密码错误");
            throw new TokenVerifyException(PermissionEnum.USER_ERROR);
        }
    }

    @Autowired
    public void setUserService(SpUserService userService) {
        this.userService = userService;
    }

}
